<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 全局注册的封装组件 -->
      <PageTools tip="213">
        <template #after>
          <el-button size="small" type="warning" @click="$router.push('/employees/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button size="small" type="primary" @click="addDialogVisible = true">新增员工</el-button>
        </template>
      </PageTools>

      <!-- 表格 -->
      <el-card style="margin: 10px 0">
        <el-table border :data="list">
          <el-table-column label="序号" sortable type="index" />
          <el-table-column label="姓名" sortable prop="username" />
          <el-table-column label="头像" sortable>
            <template slot-scope="{row}">
              <img :src="row.staffPhoto" alt="" style="border-radius: 50%; width: 100px; height: 100px; padding: 10px" @click="showCode(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式" sortable prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry">
            <template slot-scope="{ row }">
              {{ row.timeOfEntry | formatTime }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable prop="enableState" />
          <el-table-column label="操作" sortable fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" :disabled="isDisabled(point.userUpdate)" @click="$router.push('/employees/detail/' + row.id)">查看</el-button>
              <el-button type="text" size="small" :disabled="isDisabled(point.userZz)">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="onRole(row.id)">角色</el-button>
              <el-button type="text" size="small" :disabled="isDisabled(point.userDel)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="total,prev, pager, next"
            :page-size="queryData.size"
            :current-page="queryData.page"
            :total="total"
            @current-change="changePage"
          />
        </el-row>
      </el-card>

      <!-- 新增员工添加弹出框 -->
      <AddEmployees :visible.sync="addDialogVisible" @add-success="loadEmployeesList()" />

      <!-- 二维码 -->
      <el-dialog
        title="二维码"
        :visible.sync="codeDialogVisible"
        width="30%"
      >
        <el-row type="flex" justify="center">
          <canvas ref="canvas" />
        </el-row>
      </el-dialog>

      <!-- 分配角色弹出框 -->
      <assign-role v-model="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
// 全局注册
// import PageTools from '@/components/PageTools'
import { getEmployeesList } from '@/api/employees.js'
import employees from '@/api/constant/employees.js'

// 引入组件
import AddEmployees from './components/add-employees.vue'

import QRCode from 'qrcode'
import AssignRole from './components/assign-role.vue'

// 引入mixins,混入 (mixin) 提供了一种非常灵活的方式，来分发 Vue 组件中的可复用功能。
import point from '@/mixins/point'

export default {
  components: {
    // PageTools
    AddEmployees,
    AssignRole
  },
  mixins: [point],
  data() {
    AssignRole
    return {
      list: [],
      queryData: {
        page: 1, // 当前页码
        size: 5
      },
      total: 0,
      addDialogVisible: false,
      codeDialogVisible: false,
      showRoleDialog: false,
      userId: null
    }
  },

  created() {
    this.loadEmployeesList()
  },

  methods: {
    // 加载员工列表
    async loadEmployeesList() {
      const res = await getEmployeesList(this.queryData)
      // console.log(res)
      this.list = res.rows
      this.total = res.total
    },
    // 页码变化的监听
    changePage(newPage) {
      // console.log(newPage)
      this.queryData.page = newPage
      this.loadEmployeesList()
    },
    // 格式化数据（聘用形式）
    formatEmployment(row, column, cellValue, index) {
      // return cellValue === 1 ? '正式' : '非正式'
      const obj = employees.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '聘用形式错误'
    },
    // 导出excel
    exportExcel() {
      const headers = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      import('@/vendor/Export2Excel').then(async excel => {
        const { rows } = await getEmployeesList({ page: 1, size: this.total })
        // console.log(rows)
        const data = rows.map(item => {
          return Object.keys(headers).map(key => {
            // 需要判断 聘用形式字段
            if (headers[key] === 'formOfEmployment') {
              const obj = employees.hireType.find(
                obj => obj.id === item[headers[key]]
              )
              return obj ? obj.value : '未知'
            }
            return item[headers[key]]
          })
        })
        // console.log(data)

        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头 必填
          multiHeader: [['姓名', '主要信息', '', '', '', '', '部门']],
          merges: ['A1:A2', 'B1:F1', 'G1:G2'], // excel表格的行列 合并选项
          data, // 具体数据 必填
          filename: '员工信息表', // 非必填 :文件名
          autoWidth: true, // 非必填：单元格是否要自适应宽度
          bookType: 'xlsx' // 非必填 ： 文件类型
        })
      })
    },
    // 点击头像显示二维码
    showCode(url) {
      // console.log(url)
      // 没有头像链接的话不进行如何操作
      if (url) {
        this.codeDialogVisible = true
        // 数据变了，但是视图还没有，需要等页面渲染完毕后再进行操作
        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.canvas, url)
        })
      } else {
        this.$message.error('用户没有上传头像！')
      }
    },
    onRole(id) {
      // console.log(id)
      this.userId = id
      this.showRoleDialog = true
    }
  }
}
</script>

<style scoped lang='less'>
</style>
